<?php
/**
 * Created by PhpStorm.
 * User: W
 * Date: 2019/1/11
 * Time: 10:06
 */

namespace app\sports_admin\model;

use think\Request;
use think\Model;
use think\Db;
use app\sports_admin\model\Collection;
use app\exception\HeartException;

class Heart extends Model
{
    protected $table = "heart";
    protected $pk    = "heart_id";
    protected $autoWriteTimestamp = true;
    //关联教师表
    public function getTeacher()
    {
        return $this->belongsTo("Teacher","teacher_id","id")->field("teacher_name,id");
    }
    //关联收藏表
    public function getCollection()
    {
        return $this->hasMany("Collection","heart_id","heart_id");
    }

    /**
     * 教学心得
     * @param $page 页数
     * @param $rows 行数
     * @param $sort 排序字段
     * @param $sortOrder 升降序
     * @param $searchName 关键字
     */
    public static function heartList($page,$rows,$sort,$sortOrder,$searchName)
    {
        $adminList = self::with('getTeacher')
            ->where(function($query)use($searchName){if($searchName){$query->where('heart_title','like',"%{$searchName}%");}})
            ->page($page)
            ->limit($rows)
            ->order("{$sort}","{$sortOrder}")
            ->select();
        $adminCount = self::with('getTeacher')
            ->where(function($query)use($searchName){if($searchName){$query->where('heart_title','like',"%{$searchName}%");}})
            ->count();
        return ['rows'=>$adminList,'total'=>$adminCount];
    }
    /**
     *教学心得详细信息
     */
    public static function detail()
    {
        $id = Request::instance()->only('heart_id');

        return self::where('heart_id',$id['heart_id'])->find();
    }
    /**
     *修改教学心得状态
     */
    public static function updateHeart()
    {
        $data = Request::instance()->only('heart_id,heart_type');

        return self::where('heart_id',$data['heart_id'])->update(["heart_type"=>$data['heart_type']]);
    }
    /**
     * 删除教学心得
     */
    public static function delHeart()
    {
        $data = Request::instance()->only('heart_id');

        Db::startTrans();
        //先删除心得表里的心得
        $del_heart = self::where('heart_id',$data['heart_id'])->delete();
        $del_collection = Collection::where('heart_id',$data['heart_id'])->delete();
        if($del_collection && $del_heart){
            Db::commit();
            return json(['code'=>202,'msg'=>'删除成功']);
        }else{
            Db::rollback();
            throw new HeartException([
                'msg'=>'删除失败',
                'errorCode'=>400
            ]);
        }
    }

}